package com.xying.controller.backend;

import com.xying.common.ServerResponse;
import com.xying.pojo.Usr;
import com.xying.service.UsrService;
import com.xying.util.MD5Util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Hisen
 * @date 2017/11/21
 */
@Controller
public class UsrManageController {

  @Autowired
  private UsrService usrService;

  /**
   * 管理员登录
   * @param response
   * @param session
   * @param username
   * @param password
   * @return
   */
  @ResponseBody
  @RequestMapping("/manage/usr/login.do")
  public ServerResponse login(HttpServletResponse response, HttpSession session, String username, String password){
    ServerResponse<Usr> serverResponse = usrService.adminLogin(username, password);
    if (!serverResponse.isSuccess()) {
      return serverResponse;
    }

    //一个浏览器JSESSIONID相同，需要生成一个不同的
    session.setAttribute(MD5Util.MD5Encode(session.getId(), "UTF-8"), serverResponse.getData());
    return serverResponse;
  }

  /**
   * 获取用户列表
   * @param pageNum
   * @param pageSize
   * @return
   */
  @ResponseBody
  @RequestMapping("/manage/usr/list.do")
  public ServerResponse list(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize){
    return usrService.listAllUsr(pageNum, pageSize);
  }

  /**
   * 修改或更新用户信息
   * @param user
   * @return
   */
  @ResponseBody
  @RequestMapping("/manage/usr/saveOrUpdate.do")
  public ServerResponse saveOrUpdate(Usr user){
    return usrService.updateUsrInfo(user);
  }

  /**
   * 删除用户
   * @param idNo
   * @return
   */
  @ResponseBody
  @RequestMapping("/manage/usr/delete.do")
  public ServerResponse delete(String idNo) {
    return usrService.deleteUser(idNo);
  }

  /**
   * 用户搜索
   * @param userName
   * @param pageNum
   * @param pageSize
   * @return
   */
  @ResponseBody
  @RequestMapping("/manage/usr/search.do")
  public ServerResponse search(String userName,
                               @RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize){
    return usrService.searchUserName(userName, pageNum, pageSize);
  }
}
